<?php
//echo "<p>CREATE POST API</p>";
require('_base.php');

$SECRET = "baoratmoi";

// simple authentication
if(!field("secret") || field("secret")!=$SECRET) {
	header("HTTP/1.0 404 Not Found");
	//echo('{error:{code:-1,status:"Who are you?"}}');
	exit(-1);
}

header("Content-Type: application/json;");
header("Access-Control-Allow-Origin: *");

/* FIRST, CHECK IF ARTICLE ALREADY EXIST BASED ON ARTICLE ID */
// if no article_id provided, exit
if(!field('article_id')) {
	message("NO article id provided! (required)");
	return;
}

// search for articles with meta article_id
$search_query = new WP_Query(array(
	'numberposts' => -1,
	'meta_key' => 'article_id',
	'meta_value' => field('article_id')
));

// if there is at least one result, the article is imported previously
if($search_query->have_posts()) {
	message('Article is already imported');
	return;
}

/* FIRST, CREATE THE POST */

$new_post = array(
	'post_author' => 1,
	'post_status' => 'publish',
	'comment_status' => 'open'
);

// get the title
if(!field('title')) {
	message("No title information!");
	exit(-1);
} else {
	$new_post['post_title'] = wp_strip_all_tags(field('title'));
	message("Post Title: ".$new_post['post_title'],"info");
}

// get the summary
if(!field('summary')) {
	message("No summary information!");
	exit(-1);
} else {
	$new_post['post_excerpt'] = wp_strip_all_tags(field('summary'));
	message("Post Summary: ".$new_post['post_excerpt'],"info");
}

// get the content
if(!field('content')) {
	message("No content provided!");
	exit(-1);
} else {
	message('Retrieving article body content...');
	$new_post['post_content'] = unicode_conv(field('content'));
}

/**
 * POST PUBLISH DATE TIME
 */
if(field('datetime')) {
	try {
		$publish_date = date_format(new DateTime(field('datetime')),"Y-m-d H:i:s");
		$new_post['post_date'] = $publish_date;
	} catch (Exception $e) {
		message("Error parsing publish date --> set to today","error");
		$new_post['post_date'] = date_format(new DateTime(),'Y-m-d H:i:s');
	}
} else {
	message("No publish date set --> today","warning");
	$new_post['post_date'] = date_format(new DateTime(),'Y-m-d H:i:s');
}
message("Published date: ".$new_post['post_date']);

/**
 * POST CATEGORY
 */
if(field('category')) {
	$categories = explode(",",field('category'));
	$cate_names = "";
	foreach ($categories as $category) {
		$cate_names .= get_category($category,false)->name.",";
	}
	message('Set category: '.$cate_names);
	$new_post['post_category'] = $categories;
} else {
	message('No category set --> default',"warning");
}

/**
 * POST TAGS
 */
if(field('tag')) {
	$new_post['tags_input'] = explode(",",field('tag'));
	message('Post tags: '.field('tag'));
} else {
	message("No tag set","warning");
}

/**
 * CREATE POST
 */
$post_id = wp_insert_post($new_post);
message("Post created: ".$post_id,"info");

/**
 * POST THUMBNAIL
 */
if(field('thumbnail')) {
	message("Download thumbnail: ".field('thumbnail'));
	set_post_thumbnail($post_id,download_image($post_id,field('thumbnail')));
}

/**
 * DOWNLOAD ALL IMAGE IN CONTENT
 */
message('Download content images...');
$img_count = fetch_images($post_id);
message($img_count.' images downloaded!');
// message(' --> total '.$count.' image downloaded');

/**
 * POST META INFO
 */
if(field('level')) {
	message("Level Set: ".field('level'));
	update_field('field_5469e77c11eaf',field('level'),$post_id);
} else {
	update_field('field_5469e77c11eaf','1',$post_id);
}
if(field('author')) {
	message("Author: ".field('author'));
	update_field('field_5469e7bf11eb0',field('author'),$post_id);
}
if(field('source')) {
	message("Source Name: ".field('source'));
	update_field('field_5469e7e211eb1',field('source'),$post_id);
}
if(field('source_url')) {
	message("Source URL: ".field('source_url'));
	update_field('field_5469e7fc11eb2',field('source_url'),$post_id);
}
if(field('article_id')) {
	message("Article ID: ".field('article_id'));
	update_field('field_5469e81511eb3',field('article_id'),$post_id);
}

/**
 * POST FORMAT (video|gallery)
 */
if(field('format')) {
	message('Format: '.field('format'));
	set_post_format($post_id,field('format'));
}
message('=> Done!');

?>